/**
 * @author {Yuntao Zhou}
 * depend ui/uitl.js
 * depend ui/scrollpanel.js
 * depend ui/cascademenu.js
 * depend ui/dropdownlist.js
 * depend ui/tabemenu.js
 * depend ui/dataGrid.js
 * depend ui/calendar.js
 * depend ui/calendar.js
 * depend core
 * depend news_DataManager.js
 */

if(Util.DataCell){
	Util.DataCell.prototype.getValue=function(){//overwrite this method to get the originalText
		return this.originalText||this.el.children('div').html();
	};
}

if(!QSAPI){
	var QSAPI={};
}
if(!QSAPI.Widget){
	QSAPI.Widget={};
}

if(!QS_Lang){
	var QS_Lang={};
}
if(!QS_Lang.news){
	QS_Lang.news={};
}

QSAPI.Widget.News=function(container,config,callback,id){
	if(!QSAPI.DataManager){
		QSAPI.DataManager={};		
	}
	if(!QSAPI.DataManager.news){
		QSAPI.DataManager.news=new QSAPI.Widget.NewsDataManager();
	}
	this.dm=QSAPI.DataManager.news;
	
	this.container=typeof container=='string'?$('#'+container):container;
	var now=new Date();
	this.profile={
		symbolType:'all',
		productCode:'QS',
		maxCount:100,
		fixHeight:true,
		fromDate:new Date(now.getFullYear(),now.getMonth(),now.getDate()-30),
        toDate:now,
		IMGPath:'//rtqimg.morningstar.com/img/',
		
		/*header config*/
		showTab:false,
		showTabsList:false,
		showDropDownMenu:false,
		showPlusSymbol:false,
		showTickerInfo:false,
		showAutoComplete:false,
		/*content config*/
		showContent:false,
		collapseable:false,
		returnURL:false,//when click title will return content if false, or return url
		/*footer config*/
		isSaveDateRange:false,
		showDateRange:true,
		showPageTool:false,
		pageNavSize:5,
		pageSize:30,
		/*grid config*/
		sortable:false,
		colWidth:{
			'Date':'20%',
			'Subject':'79%'
		},
		
		/*auto-update*/
		updateInterval:0
	}
	
	if(config){
		$.extend(true,this.profile,config);
	}
	
	this.callback={};
	if(callback){
		$.extend(this.callback,callback);
	}
	
	this.id=id;
	
	this.HTML='<div class="qs-gd qs-news"><div class="hd head-container"></div><div class="bd"><div class="qs-r"><div class="qs-c first qs-news-headLines"><div class="grid-container"></div><div class="qs-no-news">'+(QS_Lang.news["txtnonews"]||'No news available.')+'</div><div class="qs-news-hide-link" idkey="hide">Hide</div></div><div class="qs-c qs-news-content"><div class="content-hd"></div><div class="data"></div></div></div></div><div class="ft"></div></div>';
	
	/*jquery object*/
	this.el = null; 
    this.$head=null;
    this.$headLines=null;
    this.$content=null;
    this.$hideLink=null;
    this.$gridContainer=null;
    this.$pageContainer=null;
    this.$noNewsEl=null;
	this.width=0;
	this.height=0;
	//this.ticker=null;
	//this.lastTickerObj=null;
	this.tickerArray=[];
	this.lastTickerObjArray=[];
	/*if(this.profile.width>0){
		this.width=this.profile.width;
	}else{
		this.width=0;
	}
	if(this.profile.height>0){
		this.height=this.profile.height;
	}else{
		this.height=0;
	}*/
	/*head*/
	this.head=null;
	/*foot*/
	this.foot=null;
	this.startAt=null;
    this.endAt=null;
	/*grid*/
	this.ids=[];
	this.gridCols=[];
	this.columnSet={
		'Date':{ header: QS_Lang.news["date"]||"Date",customSort:function(v1,v2){//custom the sort method
			var d1=QSAPI.Util.DateTime.convertToDate(v1);
			var d2=QSAPI.Util.DateTime.convertToDate(v2);
			if (d1 > d2) {
				return -1;
			}else if (d1 == d2) {
				return 0;
			}else{
				return 1;
			}
		}},
		'Subject':{ header: QS_Lang.news["subject"]||"Subject"},
		'Source':{ header: QS_Lang.news["source"]||"Source"}
	};
	this.newsGridList=null;
	this.selectedContentID=null;
	
	/*auto-update*/
	this.lastNewsDateTime=null;
	this.intervalObj=null;
	
	/*callback*/
	this.lastCallbackHeight=0;
	this.minHeight=260;
	this.loaded=false;
	
	this.init();
};

QSAPI.Widget.News.prototype={
	init:function(){
		var self=this;
		this.el = $(this.HTML);
        this.el.appendTo(this.container);
		this.$head=this.el.find('.head-container');
        this.$headLines=this.el.find('.qs-news-headLines');
        this.$content=this.el.find('.qs-news-content');
        this.$hideLink=this.el.find('.qs-news-hide-link');
        this.$gridContainer=this.$headLines.find('.grid-container');
        this.$pageContainer=this.el.find('.ft');
        this.$noNewsEl=this.$headLines.find('.qs-no-news');
		/*create head include tabmenu or ticker info panel or autoComplete*/
		if (this.profile.showTab||this.profile.showTicekrInfo||this.profile.showAutoComplete) {
			this._createHeader();
		}
		/*create foot include page or data range*/
		if (this.profile.showDateRange||this.profile.showPageTool) {
            this._createFooter();
			if(this.profile.showPageTool){
				this.startAt=1;
				this.endAt=this.profile.pageSize;
			}
        }
		/*create grid*/
		this.setGridCols(this.profile.colWidth);
		this._createGrid(0,0,this.gridCols);
		/*create content panel*/
		if (this.profile.fixHeight) {
            this.contentScrollPN = new Util.ScrollPanel(this.el.find('.data'));
            this.$noNewsEl.addClass('qs-no-news-fixHeighttrue');
        }else{
            this.$noNewsEl.addClass('qs-no-news-fixHeightfalse');
        }
        if (!this.profile.showContent) {
            this._collapseContent(this.profile.showContent);
        }
		/*bind event*/
		this._bindEvent();
		
		/*search news*/
		this.dm.getSourceGroupList(null,function(o){
			self.openedList=self.dm.getOpenedList(self.profile.openedList);
			self.currentSourceGroupID=self.dm.getSourceGroupID(self.profile.currentSourceGroupID,self.openedList);
			if(self.profile.ticker&&self.profile.ticker!=''){
				QSAPI.TickerFactory.create(self.profile.ticker.split(','),{
					onSuccess:function(tickerList){
						if(self.head!=null){
							self.head.activeTabById(self.currentSourceGroupID,self.getTabList());
						}
						self.acceptTicker(tickerList);
					}
				});
			}else{
				self.openView(self.currentSourceGroupID, self.dm.getSourceGroupNameByID(self.currentSourceGroupID));
			}
		})
	},
	displayAll:function(){
		if(this.profile.symbolType!='all'){
			this.profile.symbolType='all';
			//this.ticker=null;
			this.tickerArray=[];
			//this.lastTickerObj=null;
			this.lastTickerObjArray=[];
			if(this.head!=null){
				this.head.setAutoCompleteTicker('');	
			}
			this._onStateChange();
			this._searchNews();
		}
	},
	openView:function(id,txt,needActiveTab){
        this.currentSourceGroupID=id;
        if ($.inArray(id,this.openedList) < 0){
            this.openedList.push(id);
        }
		if(this.head!=null){
			this.head.activeTabById(id,this.getTabList(),needActiveTab);
		}	
		this._searchNews(true,id);
    },
	getTabList:function(){
        var tabList=[];
        var l=this.openedList.length;
        for(var i=0;i<l;i++){              
            tabList.push({
                id:this.openedList[i],
                txt:this.dm.getSourceGroupNameByID(this.openedList[i]).replace(/&/g,'&amp;'),
                closable:(!this.profile.closeable||l==1)?false:true
            });
        }
        return tabList;
    },
	setGridCols:function(colWidth){
		for(var col in colWidth){
			var cols=this.columnSet[col];
			cols.dataIndex=col;
			cols.width=colWidth[col];
			this.gridCols.push(cols);
		}
    },
	startAutoUpdate:function(needClear){
		this.stopAutoUpdate(needClear);
		if(this.profile.updateInterval>0 && QSAPI.Util.DateTime.compareWithToday(this.profile.toDate)>=0){
			this.intervalObj=this._createIntervalObj(this.profile.updateInterval);
        }
    },
    stopAutoUpdate:function(needClear){ 
        needClear=needClear===false?false:true;
        if(needClear){
            this.lastNewsDateTime='';
        }   
        if (this.intervalObj!=null) {
            clearInterval(this.intervalObj);
        }
        this.intervalObj=null;
    },
    _createIntervalObj:function(interval){  
        var self=this;
        var obj;
        var id = this.currentSourceGroupID;
        obj= setInterval(function(){
            var newsObj=self;
			var now=new Date();
            if(QSAPI.Util.DateTime.compareWithToday(self.profile.toDate)<0){
                self.profile.toDate=now;
                if (self.settingPanel != null) {
                    self.settingPanel.changeDateRangeUI(null, self.profile.toDate);
                }
				if(self.head!=null){
					self.head.changeDateRangeUI(null,self.profile.toDate);
				}
            }
            self._getPostParameter(id,function(postData){
                self.dm.getNewsTitleList(postData, function(list){
                    if(!list||list.length==0){
                        return;
                    }
                    self._addNews(newsObj,list);
                });
            },interval);
        }, interval);
        return obj;
    },
	_addNews:function(obj,list){
        if(list.length==0){
            return;
        } 
        obj.el.find('.qs-no-news').hide(); 
        var gridData = obj.createGridData(list,false);
        var rid = gridData[0].RId;
        gridData.reverse();
        var maxSize=obj.profile.showPageTool?obj.profile.pageSize:obj.profile.maxCount;
        for (var i = 0; i < gridData.length; i++) {
            obj.ids.unshift(gridData[i].RId);
            obj.newsGridList.addRow(gridData[i], gridData[i].RId, 0);
            if(obj.ids.length>maxSize){
                var lastIdx=obj.ids.length-1;
                obj.newsGridList.removeRow(obj.ids[lastIdx]);
                obj.ids.splice(lastIdx,1);
            }
        }
        if(obj.profile.showContent){
            obj.newsGridList.selectRow(rid);
        }
    },
	_searchNews:function(needShowLoading,id,afterCallback){
		var self=this;
		if(!this._isNeedSearchDB()) {
            if (typeof this.hideLoading == 'function') {
                this.hideLoading();
            }
            return;
        }
        this.startAutoUpdate();//start to auto update
        
        if (typeof id == 'undefined') {
            id = this.currentSourceGroupID;
        }
        if(typeof this.showLoading=='function'&&needShowLoading){
            this.showLoading();
        }
        this._getPostParameter(id,function(postParas){
             with ({
                tempid:id
             }){
                self.dm.getNewsTitleList(postParas, function(list){
					self.fillNews(list);
					if(typeof afterCallback=='function'){
						afterCallback();
					}
                    if (typeof self.hideLoading == 'function') {
                        self.hideLoading();
                    }
                });
             }
        });
	},
	_isNeedSearchDB:function(){
        if(this.profile.symbolType=='single'){
            if(this.tickerArray.length==0){
                return false;
            }
        }else if(this.profile.symbolType=='all'){
            if(this.tickerArray.length>0){
                return false;
            }
        }
        return true;
    },
	fillNews:function(data){
        this.el.find('.qs-no-news').hide();
        if (!data || data.length == 0 || data == null||data=='') {
            this.newsGridList.empty();
            this.$content.find('.data')[0].innerHTML='';
            this.el.find('.qs-no-news').show();
        }
        else {
            var gridData = this.createGridData(data);
            this.newsGridList.reBindData(gridData);
            if(this.profile.selectedContentID!=''&&this.profile.selectedContentID!=this.selectedContentID&&this._isContainsCurrentView()){
                this.selectedContentID=this.profile.selectedContentID;
            }else{
                this.selectedContentID=gridData[0].RId;
            }
            if(this.profile.showContent){
                this.newsGridList.selectRow(this.selectedContentID);
            }
        }
        this.changeOutSize(this.profile.width,this.profile.height);
    },
	fillNewsContent:function(data){
        this.$content.find('.data')[0].innerHTML='';
        var self=this;
        var postData={};
        postData["pTeam"]=data.pTeam;
        postData["tpl"]=data.tpl;
        postData["rId"]=encodeURIComponent(data.RId); //fix bug#1179 - david
		postData["productCode"]=this.profile.productCode;
        var date=data.date,source=data.Source,vendor=data.vendor;		
		if ((typeof workspaceManager != 'undefined'&& typeof workspaceManager.openNewsDetailWin=='function')||this.profile.showContent||!this.profile.returnURL) {
            self.dm.getNewsContent(postData, function(o){
                var tl = (o.title == null ? "" : o.title), ct = (o.content == null ? "" : o.content);
				var a =/<html.+?<body>(.+)<\/body>.*<\/html>/.exec(ct);//fix bug that some html can not display
				if(a!=null&&a.length>1){
					ct=a[1];
				}
				var str = "<div><h2>" + tl + '</h2><div class="content-bd">' + ct + '</div>';
				if (vendor == 'Briefing') {
                    str += '<div class="rtn-content-ft"><img src="'+self.profile.IMGPath+'logo_briefing.png"/><span>Copyright @ 2012 Briefing.com, Inc. All rights reserved.</span></div>';
                }else if (vendor == 'RSSFeeds') {
                    str += '<div class="rtn-content-ft" style="padding-top:5px;height:20px;">Source: ' + source + 'RSS (' + date + ')</div>';
                }else if(vendor=='Morningstar'){
                    str += '<div class="rtn-content-ft"><img src="'+self.profile.IMGPath+ 'mstar_hd.png"/><span>Copyright 2012 Morningstar, Inc. All rights reserved.</span></div>';
                }
                str += '</div>';
                if (self.profile.showContent) {
                    var contentEl = self.$content.find('.data');
                    contentEl[0].innerHTML = str;
                    contentEl.find('a').attr('target', '_blank');
                    var headFootHeight=(self.head!=null?self.head.getHeight():0)+(self.foot!=null?self.foot.getHeight():0)
					self._loadIMG(contentEl.find('img'),function(){
						self._changeContentSize(null, self.height - 24-headFootHeight);
					});
                }else{
					if(!self.profile.returnURL && typeof self.callback.onClick == 'function'){
						var ret={
							author:data.author||[],
							title:tl,
							publicationTime:data.publicationTime,
							timeZone:data.tZone,
							content:ct
						};
						self.callback.onClick(ret);
					}else{
						if(typeof workspaceManager != 'undefined'&& typeof workspaceManager.openNewsDetailWin=='function'){
							workspaceManager.openNewsDetailWin(tl, str);
						}
					}
				}
            });
        }else{
            var url=this.dm.dataURL.newsContent+"?productCode="+self.profile.productCode+"&pTeam="+data.pTeam+"&tpl="+data.tpl+"&rId="+encodeURIComponent(data.RId)+"&format=html&vendor="+vendor+"&source="+source+"&date="+date;
            if (typeof self.callback.onClick == 'function') {
                self.callback.onClick(data.Subject, url);
            }else{
                //window.open('../linkURL.jsp?u='+url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
                window.open(url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
            }
        }
    },
    fillNewsTitle:function(title,url){
        var self=this;
        this.$content.find('.data')[0].innerHTML='';
        if (this.profile.showContent) {
            this.$content.find('.data')[0].innerHTML = '<a href="javascript:void(0)"><h2 style="text-decoration:underline;" >' + title + '</h2></a>';
            this.$content.find('.data a').bind('click.news', function(e){
                self._openNewsDialog(title,url);
            });
            var headFootHeight = (this.head!=null?this.head.getHeight():0) + (this.foot != null ? this.foot.getHeight() : 0)
            this._changeContentSize(null, this.height - 24 - headFootHeight);
        }else{
            this._openNewsDialog(title,url);
        }
    },
	_loadIMG:function($img,callback){
		var imgCount=0;
		var len=$img.length;
		if (len > 0) {
			$img.bind('load', function(e){
				imgCount++;
				if(imgCount==len){
					callback();
				}
			}).bind('error', function(){
				imgCount++;
				if(imgCount==len){
					callback();
				}
			});
		}else{
			callback();
		}
	},
	_openNewsDialog:function(title,url){
        if (typeof workspaceManager != 'undefined') {
            workspaceManager.openNewsDetailWin(QS_Lang.news["newslink"]||'News Link', "<a href='" + url + "' target='_blank' ><h2 style='text-decoration:underline;' >" + title + "</h2></a>", url);
        }else{
            //window.open('../linkURL.jsp?u='+url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
            window.open(url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
        }
    },
	changeOutSize:function(w,h){
		var parent = this.el.parent();
        w = w>0?w:parent.width();
        h = h>0?h:parent.height();
        /*if(w<this.minWidth&&this.profile.instCode=='QUEST'){
            w=this.minWidth;
        }*/
        
		var flag=false;
		if(this.width!=w){
			this.width=w;
			this.profile.width=this.width;
			flag=true;
		}
		if(this.height!=h){
			this.height=h;
			this.profile.height=this.height;
			flag=true;
		}
		if(!flag){
			return;
		}
		this._onStateChange();
		var size={width:w};
        if(this.profile.fixHeight){
            size.height=h;
        }
        this.el.css(size);
        if(this.profile.fixHeight){
            var headFootHeight=(this.head!=null?this.head.getHeight():0)+(this.foot!=null?this.foot.getHeight():0)
            if(this.profile.showContent){
                this._changeHeadlinesSize(null,h-headFootHeight);
                this._changeContentSize(null,h-24-headFootHeight);
            }else{
                this._changeHeadlinesSize(null,h-headFootHeight);
                this.$content.hide();
                this.$hideLink[0].innerHTML='Show';
                this.$hideLink.attr('idkey','show');
            }
        }
        var height=this.el.height();
        this.onHeightChange(height);
        if(this.head&&this.head.tabMenu&&typeof(this.head.tabMenu.reSize)=="function"){
            this.head.tabMenu.reSize();
        }
    },
    _changeHeadlinesSize:function(w,h){
        var size={};
        if(w>0){
            size.width=w;
        }
        if(h>0){
            size.height=h;
        }
        this.$gridContainer.css(size);
        this.newsGridList.resize(null,h);
    },
    _changeContentSize:function(w,h){
        if(this.profile.fixHeight){
           var size={};
            if(w>0){
                size.width=w;
            }
            if(h>0){
                size.height=h;
            }
            this.$content.find('.data').css(size);
            this.contentScrollPN.reSize(null,h);
        }
        var height=this.el.height();
        this.onHeightChange(height);
    },
	onHeightChange:function(height){
        if(height<this.minHeight){
            height=this.minHeight;
        }
        if (!this.loaded) {
            this.lastCallbackHeight = height;
            if (typeof this.callback.onLoad == 'function') {
                this.loaded = true;
                this.callback.onLoad({
                    component: 'news',
                    height: height,
                    //minWidth:this.minWidth,
                    minHeight:this.minHeight
                });
            }
        }else {
            if (this.lastCallbackHeight != height) {
                this.lastCallbackHeight = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: this.lastCallbackHeight,
                        component: 'news'
                    });
                }
            }
        }
    },
	changeDateRange:function(s,e){
        var flag=false;
        if(this.profile.fromDate!=s){
            this.profile.fromDate=s;
            flag=true;
        }
        if(this.profile.toDate!=e){
            this.profile.toDate=e;
            flag=true;
        }
        if (flag) {
			this._onStateChange();		
            this.stopAutoUpdate();
            if(typeof this.showLoading=='function') {
                this.showLoading(true);
            }
            this._searchNews(false,this.currentSourceGroupID);
        }
    },
	createGridData:function(data,needAddIds){
        needAddIds=needAddIds===false?false:true;
        var result=[];
        var len=data.length,subject,sName,rId,vendor,dTime;
        for(var i=0;i<len;i++){
            var obj=data[i];
            sName=obj.sName;
            subject=obj.title;
            vendor=obj.vendor;
			rId=obj.cId||'';
            if(i==0){
                this.lastNewsDateTime=this._getLastNewsDateTime(obj.dTime);
            }
            if(sName!=''){  //fixed bug#1178 - david
                var idx=subject.indexOf("["+sName+"]");
                if(idx>=0){
                    subject=subject.substring(0,idx);
                }
            }
			if(!this.profile.colWidth['Source']&&sName!=''){
				subject=subject+"&nbsp; ["+(vendor!='Acquire'?vendor+" - ":'')+sName+"]";
			}
			
            dTime=QSAPI.Util.DateTime.toDateTime(obj.dTime);
            result.push({
                Date:dTime,
                Subject:subject,
                RId:rId,
                Url:obj.cURL||'',
                Source:sName,
                pTeam:obj.pTeam||'',
                tpl:obj.tpl,
                vendor:vendor,
                publicationTime:obj.dTime,
				tZone:obj.tZone||''
            });
            if (needAddIds){
                this.ids.push(rId);
            }
        }
        return result;
    },
	_getLastNewsDateTime:function(d){//add one seconds for the date time of last news
		var arr=d.split(':'),
            s=parseInt(arr[2])+1;
        s=s<10?('0'+s):s;
        arr[2]=s;
        return arr.join(":");
	},
	_getDateConfig:function(interval){
		var needTranserfer=true;
		var fromDate=QSAPI.Util.DateTime.setTime(this.profile.fromDate);
		var toDate=QSAPI.Util.DateTime.setTime(this.profile.toDate,'max'); 
		if(QSAPI.Util.DateTime.compareWithToday(this.profile.toDate)>=0){
			if(interval>0 && this.lastNewsDateTime!=null){
				needTranserfer=false;
				fromDate=this.lastNewsDateTime;
			}
		}	
		return {    
			from:needTranserfer?QSAPI.Util.DateTime.formatDateTime(fromDate):fromDate,
			to:QSAPI.Util.DateTime.formatDateTime(toDate)
		}
    },
	_getPostParameter:function(id,callback,interval){
        var self=this;
        var config=this._getDateConfig(interval);
        var postData={
			productCode:this.profile.productCode,//'QS',
            lang:'en'
        };
		if(config.from&&config.to){
			postData['fromDate']=config['from'];
			postData['toDate']=config['to'];
		}
        if(this.profile.showPageTool){
			if(interval>0){
				postData['startAt']=1;
				postData['endAt']=this.profile.pageSize;
			}else{
				postData['startAt']=this.startAt;
				postData['endAt']=this.endAt;
			}
        }else{
            postData['maxCount']=this.profile.maxCount;
        }
		if(this.tickerArray.length>0){
			postData["symbols"]=this.tickerArray.join(',');
			postData["idType"]='SC';
		}
		this.dm.getSourceGroupByID(id,function(o){
			$.extend(postData, self._formatSourcesPara(o));
			callback(postData);
		});	
    },
	_formatSourcesPara:function(s){
		var sources={},nts,dcs;
        if(typeof s!='undefined'){
            nts=s["ntSource"],dcs=s["dcSource"];
        }
        if(nts!=null&&nts.length!=0){
            sources["ntSourceCode"]=nts.join(',');
        }
        if(dcs!=null&&dcs.length!=0){
            sources["dcSourceCode"]=dcs.join(',');
        }
        return sources;
	},
	_bindEvent:function(){
        if (this.profile.collapseable) {
            var self = this;
            this.el.bind('click.News', function(e){
                var target = $(e.target);
                if (target.hasClass('qs-news-hide-link')) {
                    var key = target.attr('idkey');
                    var flag = true;
                    if (key == 'hide') {
                        flag = false;
                    }
                    self._collapseContent(flag);
                    self.changeOutSize(self.width, self.height);
                }
            });
        }else{
            this.$hideLink.hide();
        }
    },
	_collapseContent:function(flag){
        if(flag){
            this.$content[0].style.display='block';
            this.el.find('.qs-c').css('width','49.94%');
            this.$hideLink[0].innerHTML='Hide';
            this.$hideLink.attr('idkey','hide');
        }else{
            this.$content[0].style.display='none';
            this.el.find('.qs-c').eq(0).css('width','100%');
            this.$hideLink[0].innerHTML='Show';
            this.$hideLink.attr('idkey','show');
        }
        this.profile.showContent=flag;
        if (this.profile.showContent){
             this.newsGridList.selectRow(this.selectedContentID);
        }
    },
	_isContainsCurrentView:function(){
        if(this.ids.length==0||this.profile.selectedContentID==''){
            return false;
        }
        if($.inArray(this.profile.selectedContentID,this.ids)>=0){
            return true;
        }else{
            return false;
        }
    },
	_createGrid:function(w,h,cols){
        var self=this;
        this.newsGridList=new Util.DataGrid(this.$gridContainer,{},{
            column:cols,
            fixSize:false,
            width:w>0?w:0,
            height:h>0?h:0,
            htmlLayer:'div',
            indexColKey:'RId',
            sortable: this.profile.sortable,
            cellResize: false,
            cellRearrange: false,
            rowInvertSelect:false,
            autoWidth:true,
            autoHeight:!this.profile.fixHeight
        },{
            onRowSelected: function(e, row){
                var url = row.data.Url,pTeam=row.data.pTeam, subject = row.data.Subject;
                self.selectedContentID = row.data.RId;
				var flag=false;
				if(pTeam=='DC'){
					if(url==''){
						flag=true;
					}
				}else{
					if(self.selectedContentID.length>0){
						flag=true;
					}
				}
				if(flag){
					self.fillNewsContent(row.data);
				}else{
					self.fillNewsTitle(subject, url);
				}
            }
        });
    },
	_createHeader:function(){
        var self=this;
        this.head=new QSAPI.Widget.NewsHeader(this,{
			needRemember:false,
			focusClear:false
		},this.$head,{
			showAutoComplete:this.profile.showAutoComplete,
            showTab:this.profile.showTab,
            tabsList:this.profile.showTabsList,
            showTickerInfo:this.profile.showTickerInfo,
            hasDropDownMenu:this.profile.showDropDownMenu,
            plusSymbol:this.profile.plusSymbol
        },{
            onTabAfterRearrange:function(tab,ids){
                var newOpenList = [];
                //reorder openedlist
                for (var j = 0; j < ids.length; j++) {
                    for (var i in self.openedList) {
                        if (self.openedList[i] == ids[j]) {
                            newOpenList.push(self.openedList[i]);
                        }
                    }
                }
                self.openedList = newOpenList.slice();
            },
            onTabActive:function(tab){
                if(self.currentSourceGroupID!=tab.id){
                    self.openView(tab.id,tab.txt);
                }   
            },
            onTabDeActive:function(tab){
                self.stopAutoUpdate();
            },
            onTabBeforeClose:function(tab){
                self.closeView(tab.id);
            },
			onAutoCompleteClick:function(tickerObj){
				self.acceptTicker(tickerObj);
			}
        },this.id);
    },
	
	_createFooter:function(){
        var self=this;
        this.foot=new QSAPI.Widget.NewsFooter(this.$pageContainer,{
            fromDate:this.profile.fromDate,
            toDate:this.profile.toDate,
            hasPaging:this.profile.showPageTool,
            hasDatePicker:this.profile.showDateRange,
            navSize:this.profile.pageNavSize,
			pageSize:this.profile.pageSize
        },{
            onPageChanged:function(startAt,endAt){
                self.startAt=startAt;
                self.endAt=endAt;
                self._searchNews(true);
            },
            onDateChanged:function(s,e){
                self.changeDateRange(s,e);
            }
        });
    },
	_onStateChange:function(){
		if(typeof this.callback.onStateChange=='function'&&this.loaded){
			this.callback.onStateChange();
		}
	},
	saveConfig:function(){
		var config={
            width: this.width,
            height: this.height
        };
		if(this.tickerArray.length>0){
			config.ticker=this.tickerArray.join(',');
		}
		if(this.profile.isSaveDateRange){//if user check the save,it will be saved.
            config.toDate=QSAPI.Util.DateTime.formatDate(this.profile.toDate);
            config.fromDate=QSAPI.Util.DateTime.formatDate(this.profile.fromDate);          
        }
		return config;
	},
	/*loadConfig:function(config){
		if(config.ticker!=null&&config.ticker!=''){
			this.ticker=ticker;
		}
		if(config.fromDate&&config.toDate){
			this.profile.fromDate=QSAPI.Util.DateTime.convertDate(config.fromDate);
			this.profile.toDate=QSAPI.Util.DateTime.convertDate(config.toDate);
		}
		if(config.width>0){
			this.width=config.width;
		}
		if(config.height>0){
			this.height=config.height;
		}
		this._searchNews();
	},*/
	
	_getPidsOfTickers:function(tickers){
		var pids=[],ticker,pid,isContainsCount=this.tickerArray.length;
		for(var i=0,l=tickers.length;i<l;i++){
			ticker=tickers[i];
			pid=ticker.getField('performanceId');
			if(pid&&pid!=""){
				if(this.tickerArray.length>0&&$.inArray(pid,this.tickerArray)!=-1){
					isContainsCount--;
				}
				pids.push(pid);
			}
		}
		if(pids.length!=this.tickerArray.length){
			return pids;
		}else{
			return isContainsCount==0?null:pids;
		}
	},
	
	_getClientTickers:function(){
		var clientTicker='';
		if(this.lastTickerObjArray.length>0){
			var cts=[],t='';
			for(var i=0,l=this.lastTickerObjArray.length;i<l;i++){
				t=this.lastTickerObjArray[i].getField('clientTicker')||this.lastTickerObjArray[i].getField('ticker');
				if(typeof t!='undefined' && t!=''){
					cts.push(t)
				}
			}
			if(cts.length>0){
				clientTicker=cts.join(',');
			}
		}
		return clientTicker;
	},
	
	/**ticker is an array of instance of QSAPI.Ticker or instance of QSAPI.Ticker, support v1.1*/
	acceptTicker:function(ticker){
		var self=this, tickers=$.isArray(ticker)?ticker:[ticker];
		var pids=this._getPidsOfTickers(tickers);
		if(pids!=null){//if null, means that the ticker is same with last ticker.
			if(pids.length==0){// if length is 0, means no one ticker has the performanceId
				if(this.head!=null){
					this.head.setAutoCompleteTicker(this._getClientTickers());	
				}
				Util.message(QS_Lang.news["txtinvalidticker"]||"Invaid ticker");
			/*}else if(pids.length==1){
				this.profile.symbolType='single';
				this._onStateChange();
				this.lastTickerObj=ticker;
				this.ticker=ticker.getField('performanceId');
				this.lastTickerObjArray=[];
				this.tickerArray=[];
				this._searchNews(true,this.currentSourceGroupID,function(){
					if(self.head!=null){
						self.head.setAutoCompleteTicker(self._getClientTickers());	
					}
				*/
			}else{				
				this.profile.symbolType='single';
				this._onStateChange();
				//this.lastTickerObj=null;
				//this.ticker=null;
				this.lastTickerObjArray=tickers;
				this.tickerArray=pids;
				this._searchNews(true,this.currentSourceGroupID,function(){
					if(self.head!=null){
						self.head.setAutoCompleteTicker(self._getClientTickers());	
					}
				});
			}
		}
		
		/*var pid=ticker.getField('performanceId');
		if(pid&&pid!=""){
			if(pid!=this.ticker){
				this.profile.symbolType='single';
				this._onStateChange();
				this.lastTickerObj=ticker;
				this.ticker=ticker.getField('performanceId');
				this._searchNews(true,this.currentSourceGroupID,function(){
					if(self.head!=null){
						self.head.setAutoCompleteTicker(self.lastTickerObj.getField('clientTicker')||self.lastTickerObj.getField('ticker')||'');	
					}
				});
			}
		}else{
			if(this.head!=null){
				this.head.setAutoCompleteTicker(this.lastTickerObj.getField('clientTicker')||this.lastTickerObj.getField('ticker')||'');	
			}
			Util.message(QS_Lang.news["txtinvalidticker"]||"Invaid ticker");
		}*/
	}
};


QSAPI.Widget.NewsHeader=function(newsObj,newsCustomViewObj,container,config,callback,id){
    this.newsObj=newsObj;
	this.newsCustomViewObj=newsCustomViewObj;
    this.el=null;
    this.container=container;
	this.id=id;
	this.autoComplete=null;
	this.autoCompleteId=null;
    this.tabMenu=null;
    this.ddMenu=null;
    this.$tabMenu=null;
    this.$ticekrInfo=null;
    this.activeTabId=null;
    this.tabList=null;
    this.html='<div class="qs-news-hd"><div class="tabMenu"></div><div class="tickerInfo"><h1 class="name"></h1><span class="symbol"></span><span class="rate"></span></div></div>';
    this.config={
		showAutoComplete:false,
        showTab:true,
        tabsList:true,
        showTickerInfo:false,
        rearrangeTabable:true,
        hasDropDownMenu:true,
        plusSymbol:false
    };
    this.callback={
		onAutoCompleteClick:null,//function(tickerObj){}
		onAutoCompleteSubmit:null,//function(tickerObj){}
        onTabActive:null,//function(tab){}
        onTabDeActive:null,//function(tab){}
        onTabBeforeClose:null,//function(tab){}
        onTabAfterClose:null,//function(tab){}
        onTabAfterRearrange:null//function(tab,tabIds){}
    };
    if(config){
        $.extend(this.config,config);
    }
    if(callback){
        $.extend(this.callback,callback);
    }
    this.init();
};

QSAPI.Widget.NewsHeader.prototype={
    init:function(){
        this.el=$(this.html).appendTo(this.container);
        this.$tabMenu=this.el.find('.tabMenu');
        this.$ticekrInfo=this.el.find('.tickerInfo');
		if(this.config.showAutoComplete){
			this.autoCompleteId=this.id+"_news_autocomplete";
			var autoCompleteContainer=$('<div class="news-head-autocomplete"></div>').prependTo(this.el);
			this._createAutoComplete(autoCompleteContainer,this.autoCompleteId);
		}
		this._createTabMenu();
		if(!this.config.showTab){
			this.$tabMenu.hide();
		}
        if(this.config.hasDropDownMenu){
            this._createDDMenu();
        }
        if(!this.config.showTickerInfo){
            this.hideTicekrInfo();
        }         
    },
	_createAutoComplete:function(container,id){
		var self=this;
		this.autoComplete=QSAPI.Widget.AutoComplete(container,{
			showInput:true
		},{
			onClick:function(tickerObj){
				if(typeof self.callback.onAutoCompleteClick=='function'){
					self.callback.onAutoCompleteClick(tickerObj);
				}
			},
			onSubmit:function(tickerObj){
				if(typeof self.callback.onAutoCompleteSubmit=='function'){
					self.callback.onAutoCompleteSubmit(tickerObj);
				}
			}
		},id);
	},
	setAutoCompleteTicker:function(ticker){
		if(this.autoComplete!=null){
			this.autoComplete.setTicker(this.autoCompleteId,{ticker:ticker});
		}
	},
    getHeight:function(){
		return this.el.outerHeight(true);		
    },
    getDDMenuData:function(id){
        id=id||this.activeTabId;
        var arr=[{
            type: 'separator'
        },{
            txt: 'New View...',
            val: 'cv_add'
        }];
        return [{
            txt: 'News Views',
            val: '',
            className: 'subtitle'
        },id<0?null:{
            txt: 'Edit...',
            val: 'cv_edit'
        },id<0?null:{
            txt: 'Delete',
            val: 'cv_del'
        }, {
            txt: 'Morningstar Views',
            val: 'msview',
            subMenu: typeof GB_NewsDataManager!='undefined'?GB_NewsDataManager.getDefaultViewListByGroup('msview'):[]
        }, {
            txt: 'My Views',
            val: 'myview',
            subMenu: typeof GB_NewsDataManager!='undefined'?GB_NewsDataManager.getDefaultViewListByGroup('myview').concat(arr):[]
        }];
    },
    rebindDropDownMenu:function(tab){
        var self=this;
        if (tab) {
            var menuData = self.getDDMenuData();
            self.ddMenu.reBind(menuData);
            var xy = tab.menu.position();
            var winObj=self.newsObj.__winObj;
            if (winObj&&winObj.widget&&winObj.widget != self.newsObj) {//judge if it was in sr.
                var sr = winObj.widget;
                self.ddMenu.setPosition(xy.left + 10 + sr.widthCol1, xy.top +76 + sr._getBoxHeight(3));
            }
            else {
                self.ddMenu.setPosition(xy.left, xy.top + 46);
            }
            self.ddMenu.show();         
        }
    },
    _createDDMenu:function(){
        var self=this;
        var el=this.newsObj.__winObj?this.newsObj.__winObj.toolPanel:this.$tabMenu[0];
        this.ddMenu = new Util.CascadeMenu(el, {
            display: false,
            autoHide: true
        }, this.getDDMenuData(), {
            onClick: function(item){
                switch (item.data.val) { 
                    case 'cv_add':
                        self.newsCustomViewObj.create(self.newsObj);
                        break; 
                    case 'cv_edit':
                        self.newsCustomViewObj.edit(self.newsObj,self.activeTabId);
                        break;
                    case 'cv_del':
                        self.newsCustomViewObj.remove(self.newsObj,self.activeTabId);          
                        break;
                    case 'msview':                
                    case 'myview':
                        if (item.data.vid != self.activeTabId) {
                            self.newsObj.openView(item.data.vid, item.data.txt);
                        }
                        break;
                }
                self.ddMenu.hide();
            }
        });
    },
    bindDDMenutoTab:function(tab){
        var self=this;
        tab.menu.bind('mouseover.tabnewsddl', function(){
            self.rebindDropDownMenu(tab);
        }).bind('mouseout.tabnewsddl', function(){
            self.ddMenu.hide();
        });
    },
    unBindDDMenuFromTab:function(tab){
        tab.menu.unbind('.tabnewsddl');
    },
    _createTabMenu:function(){
        var self=this;
        this.tabMenu=new Util.TabMenu(this.$tabMenu[0],[], {
            onActive: function(tab){
                if (self.config.hasDropDownMenu) {
                    self.bindDDMenutoTab(tab);
                }
                if(typeof self.callback.onTabActive=='function'){
                    self.callback.onTabActive(tab);
                }

            },
            onDeActive:function(tab){
                if(typeof self.callback.onTabDeActive=='function'){
                    self.callback.onTabDeActive(tab);
                }  
            },
            beforeClose: function(tab){
                if(typeof self.callback.onTabBeforeClose=='function'){
                    self.callback.onTabBeforeClose(tab);
                }
            },
            afterClose:function(tab){
                var tabCount = 0;
                for (var i = 0, l = self.tabMenu.tabs.length; i < l; i++) {
                    if (!self.tabMenu.tabs[i].isClose) {
                        tabCount++;
                        if(tabCount=1){
                            self.tabMenu.tabs[0].menu.addClass('noclose');
                        }
                    }
                }
                self.unBindDDMenuFromTab(tab);
                if(typeof self.callback.onTabAfterClose=='function'){
                    self.callback.onTabAfterClose(tab);
                }
                
            },
            onAddTab:function(){
                self.newsCustomViewObj.create(self.newsObj);
                //console.log(workspaceManager.openWorkspaceManager);
                //workspaceManager.openWorkspaceManager();
            },
            afterRearrange: function(tab){
                var ids = self.tabMenu.getIdList();
                if(typeof self.callback.onTabAfterRearrange=='function'){
                    self.callback.onTabAfterRearrange(tab,ids);
                }
            }
        },{
            width: 100,
            marginRightWidth:26,
            plusSymbol:this.config.plusSymbol,
            autoResize: false,
            tabsList:this.config.tabsList,
            autoFixtoText: true,
            isExcuteCallbackAtInit: false,
            closeAction: 'hide',
            autoSlideToActiveTab: true,
            rearrange: this.config.rearrangeTabable
        });
    },
    activeTabById:function(id,tabList,needActiveTab){
        this.activeTabId=id;
        this.tabMenu.cfg.activeTabId = id;
        this.tabMenu.reBindData(tabList);
        if(needActiveTab) {
           this.tabMenu.getTabById(id).active(null, true);
        }
        this.tabMenu.showActiveTab(); 
        if(this.config.hasDropDownMenu){
            this.bindDDMenutoTab(this.tabMenu.currentTab);
        }
    },
    show:function(){
//      if(this.config.showTab) {
//          this.showTabMenu();
//      }
//      if(this.config.showTickerInfo){
//          this.showTicekrInfo();
//      }
        this.el.show();
    },
    hide:function(){
//      if(!this.config.showTab) {
//            this.hideTabMenu();
//        }
//        if(!this.config.showTickerInfo){
//            this.hideTicekrInfo();
//        }
        this.el.hide();
    },
    showTabMenu:function(){
        //this.config.showTab=true;
        this.$tabMenu.show();
    },
    hideTabMenu:function(){
        //this.config.showTab=false;
        this.$tabMenu.hide();
    },
    showTicekrInfo:function(){
        //this.config.showTickerInfo=true;
        this.$ticekrInfo.show();
    },
    hideTicekrInfo:function(){
        //this.config.showTickerInfo=false;
        this.$ticekrInfo.hide();
    },
    getConfig:function(){
        return this.config;
    },
    updateTickerInfo:function(type,gkey){
        if(!this.config.showTickerInfo){
            return;
        }
        var self=this;
        if (type == 'single') {
            this.showTicekrInfo();
            var gd = gData[gkey];
            this.$ticekrInfo.find('.name')[0].innerHTML = gd.Name || "";
            this.$ticekrInfo.find('.symbol')[0].innerHTML = " " + gd.clientTicker||gd.ticker;
            getStaticData([gd.secId], function(){
                if (gd["st200"] != '') {
                    var cls = "sstar" + gd["st200"]
                    self.$ticekrInfo.find('.rate').addClass(cls);
                }
            });
        }else{
            this.hideTicekrInfo();
        }
    },
    clear:function(){
        this.el.unbind(".tabnewsddl");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};

QSAPI.Widget.NewsFooter=function(container,config,callback){
    this.container=container;
	var now=new Date();
    this.config={
        hasPaging:false,
        hasDatePicker:false,
        pageSize:30,
        navSize:5,
        fromDate:now,
        toDate:now
    };
    this.callback={
        onDateChanged:null,//function(s,e){}
        onPageChanged:null//function(s,e){}
    };
    if(config){
        $.extend(this.config,config);
    }
    if(callback){
        $.extend(this.callback,callback);
    }
    this.el=null;
    this.$datePicker=null;
    this.$dateInput=null;
    this.$page=null;
    this.html='<div class="qs-news-pageNavigation">'+(this.config.hasDatePicker?'<span class="date-picker"><input class="qs-ui-ipt" type="text" readOnly=true/> - <input class="qs-ui-ipt" type="text" readOnly=true /> <a class="qs-ui-btn go" href="javascript:void(0)">'+(QS_Lang.news["go"]||'GO')+'</a></span>':'')+(this.config.hasPaging?'<span class="page"></span>':'')+'</div>';
    this.init();
};
QSAPI.Widget.NewsFooter.prototype={
    init:function(){
        this.el=$(this.html).appendTo(this.container);
        if (this.config.hasPaging) {
             this.$page=this.el.find('.page');
            this._createPage(this.$page);
        }
        if (this.config.hasDatePicker){
            this.$dateInput=this.el.find('.date-picker input');
            this.$dateSearch=this.el.find('.date-picker .go');
            this._createDateRange(this.$dateInput);
        }
    },
    getHeight:function(){
        return this.el.outerHeight(true);
    },
    _createPage:function(container){
        var self=this;
        var page=new Util.PageUtil(container,{
            onClick:function(startAt,endAt){
                 if(typeof self.callback.onPageChanged=='function'){
                    self.callback.onPageChanged(startAt,endAt);
                 }
            }
        },{
            navSize:this.config.navSize,
            pageSize:this.config.pageSize
        });
    },
	changeDateRangeUI:function(s,e){
		if(!this.config.hasDatePicker) return;
        if(s!=null){
            this.$dateInput.eq(0).data('date',s).val(QSAPI.Util.DateTime.formatDate(s));  
        }
        if(e!=null){
            this.$dateInput.eq(1).data('date',e).val(QSAPI.Util.DateTime.formatDate(e));  ;
        }
    },
    _createDateRange:function(dateInput){
        var self=this;
        dateInput.eq(0).val(QSAPI.Util.DateTime.formatDate(this.config.fromDate)).data('date',this.config.fromDate);
        dateInput.eq(1).val(QSAPI.Util.DateTime.formatDate(this.config.toDate)).data('date',this.config.toDate);
        if(typeof QSCAL=='undefined'){
            var QSCAL = new Util.Calendar($('body'),{},{
                direction:'top'
            });
        }
        QSCAL.register(dateInput[0],function(date){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if (date.getTime() > edt.getTime()) {
                dateInput.eq(0).data('date',edt);
                dateInput.eq(1).data('date',date).val(QSAPI.Util.DateTime.formatDate(date));
            }else {
                dateInput.eq(0).data('date',date);
            }
            dateInput.eq(0).val(QSAPI.Util.DateTime.formatDate(dateInput.eq(0).data('date')));         
        });
        QSCAL.register(dateInput[1],function(date){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if(date.getTime()<sdt.getTime()){
                dateInput.eq(1).data('date',sdt);
                dateInput.eq(0).data('date',date).val(QSAPI.Util.DateTime.formatDate(date));
            }
            else{
                dateInput.eq(1).data('date',date);
            }
            dateInput.eq(1).val(QSAPI.Util.DateTime.formatDate(dateInput.eq(1).data('date')));  
        });
        dateInput.focus(function(e){
            if ($.browser.msie) {       // fixed the issue that hit backspace key will back the web page.
                document.body.focus();
            }
            QSCAL.show(e.target,$(e.target).data('date'));      
        });
        this.$dateSearch.bind('click.newNav',function(e){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if(typeof self.callback.onDateChanged=='function'){
                self.callback.onDateChanged(sdt,edt);
            }  
        });
    },
    clear:function(){
        QSCAL.unregister(this.$dateInput[0]);
        QSCAL.unregister(this.$dateInput[1]);
        this.el.unbind(".newNav");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};